<template>
  <div>
    <el-divider content-position="left">课程信息</el-divider>
    <!--表格1 课程信息-->
    <div v-if="tableShow">
      <el-table
        :cell-class-name="tableCellClassName"
        :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
        border
        stripe
        height="450"
        style="width: 100%; margin-top: 20px"
        @cell-click="cell_click"
      >
        <el-table-column
          prop="courseName"
          label="课程名"
          sortable
          min-width="70"
        />
        <el-table-column
          prop="hours"
          label="学时"
          sortable
          min-width="50"
        />
        <el-table-column
          prop="credit"
          label="学分"
          sortable
          min-width="50"
        />
        <el-table-column
          prop="classCount"
          label="班级数目"
          sortable
          min-width="60"
        />
        <el-table-column
          prop="studentCount"
          label="选课总人数"
          sortable
          min-width="70"
        />
        <el-table-column
          prop="teachers"
          label="授课教师"
          sortable
          min-width="60"
        />

        <el-table-column
          align="right"
          width="200"
        >
          <template slot="header" slot-scope="scope">
            <el-input
              v-model="search"
              size="mini"
              placeholder="输入关键字搜索"
            />
          </template>
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="currentTable = 1; handleEdit(scope.$index, scope.row, 1)"
            >编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="currentTable = 1; handleDelete(scope.$index, scope.row, 1)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--分页控件1-->
    <div class="block">
      <!--按钮组-->
      <div>
        <el-button
          type="primary"
          size="small"
          @click="currentTable=1; dialog = true; title = '新增课程信息'; form.id = form.name = form.hours = form.credit = ''"
        >新增课程信息
        </el-button>
      </div>
      <el-pagination
        :current-page="table_1.current"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="table_1.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="table_1.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-divider content-position="left">课程班级信息</el-divider>
    <!--表格2 课程信班级息-->
    <div v-if="tableShow">
      <el-table
        :data="tableData2"
        border
        stripe
        height="300"
        style="width: 100%; margin-top: 20px"
      >
        <el-table-column
          prop="classNum"
          label="班级"
          sortable
          min-width="50"
        />
        <el-table-column
          prop="name"
          label="班级名称"
          sortable
          min-width="50"
        />
        <el-table-column
          prop="teacherName"
          label="授课教师"
          sortable
          min-width="60"
        />

        <el-table-column
          align="right"
          width="200"
        >
          <template slot="header" slot-scope="scope">
            <el-input
              v-model="search"
              size="mini"
              placeholder="输入关键字搜索"
            />
          </template>
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="currentTable = 2; handleEdit(scope.$index, scope.row, 2)"
            >编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="currentTable = 2; handleDelete(scope.$index, scope.row, 2)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-button
        type="primary"
        size="small"
        @click="currentTable=2; dialog = true; title = '新增课程班级信息'; form.id = form.name = form.hours = form.credit = ''"
      >新增课程班级
      </el-button>
    </div>
    <!--抽屉-->
    <el-drawer
      ref="drawer"
      :title="title"
      :before-close="handleClose"
      :visible.sync="dialog"
      direction="rtl"
      custom-class="demo-drawer"
    >
      <div class="demo-drawer__content">
        <div v-if="title.toString().includes('班级')">
          <el-form :model="form">
            <el-form-item label="班级序号" :label-width="formLabelWidth">
              <el-input v-model="form.classNum" autocomplete="off" />
            </el-form-item>
            <el-form-item label="班级名称" :label-width="formLabelWidth">
              <el-input v-model="form.name" autocomplete="off" />
            </el-form-item>
            <!--<el-form-item label="授课教师" :label-width="formLabelWidth">-->
            <!--  <el-input v-model="form.teacherName" autocomplete="off" />-->
            <!--</el-form-item>-->
            <el-form-item label="授课教师" :label-width="formLabelWidth">
              <el-select v-model="form.teacherId" placeholder="请授课教师">
                <el-option v-for="teacher in teacherData" :label="teacher.nickname" :value="teacher.id" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div v-else>
          <el-form :model="form">
            <el-form-item label="课程名" :label-width="formLabelWidth">
              <el-input v-model="form.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="学时" :label-width="formLabelWidth">
              <el-input v-model="form.hours" autocomplete="off" />
            </el-form-item>
            <el-form-item label="学分" :label-width="formLabelWidth">
              <el-input v-model="form.credit" autocomplete="off" />
            </el-form-item>
          </el-form>
        </div>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button type="primary" :loading="loading" @click="$refs.drawer.closeDrawer()">
            {{ loading ? '提交中 ...' : '确 定' }}
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
// 引入自己编写的接口 src/api/course.js
import apiCourse from '@/api/course'
import apiCourseClass from '@/api/courseClass'
import apiTeacher from '@/api/teacher'

export default {
  data() {
    return {
      tableData: [{
        id: 0,
        'courseName': 'Java Web',
        'hours': 64,
        'credit': 3.0,
        'classCount': 5,
        'studentCount': 10,
        'teachers': '刘继光,兰全祥'
      }],
      // 课程班级表格数据
      // {
      //   "id": 1,
      //   "courseId": 1,
      //   "classNum": 1,
      //   "name": "Java Web No.1",
      //   "teacherId": 1
      // }
      tableData2: [{
        classNum: 1,
        course_id: 1,
        id: 1,
        name: 'Java Web No.1',
        teacherName: '兰全祥',
        teacher_id: 1
      }],
      teacherData: [{
        nickname: '兰全祥',
        id: 1,
        username: ''
      }],
      table_1: {
        total: 4,
        size: 2,
        current: 1,
        orders: [],
        searchCount: true,
        pages: 2
      },
      table_2: {
        total: 4,
        size: 50,
        current: 1,
        orders: [],
        searchCount: true,
        pages: 2
      },
      search: '',
      tableShow: true,
      //  弹出框
      table: false,
      dialog: false,
      loading: false,
      // 课程信息表单
      form: {
        id: '',
        name: '',
        hours: '',
        credit: '',
        delivery: false,
        type: [],
        courseId: '',
        classNum: '',
        teacherName: '',
        teacherId: 1
      },
      // 课程班级信息表单
      // {
      //   "id": 1,
      //   "courseId": 1,
      //   "classNum": 1,
      //   "name": "Java Web No.1",
      //   "teacherId": 1
      // }
      formLabelWidth: '80px',
      timer: null,
      currentTable: 1,
      title: '新增课程信息',
      currentIndex: 1,
      myrow: null
    }
  },
  mounted() {
    this.load(this.table_1.current, this.table_1.size)
  },
  methods: {
    // 加载表格数据
    load(currentpage, pagesize) {
      console.log(currentpage + '---' + pagesize)
      apiCourse.getList({ 'currentPage': currentpage, 'size': pagesize }).then(res => {
        console.log(res)
        this.tableData = res.data.records
        this.table_1.total = res.data.total
        this.table_1.size = res.data.size
        this.table_1.current = res.data.current
        this.table_1.pages = res.data.pages
        this.table_1.orders = res.data.orders
      })
    },
    // 加载表格2数据
    load_2(currentpage, pagesize) {
      apiCourse.getCourseClass({ 'currentPage': currentpage, 'size': pagesize }, this.myrow.id).then(res => {
        console.log(res)
        this.tableData2 = res.data.records
        this.table_2.total = res.data.total
        this.table_2.size = res.data.size
        this.table_2.current = res.data.current
        this.table_2.pages = res.data.pages
        this.table_2.orders = res.data.orders
        // alert('更新了表格')
      })
      apiTeacher.getList().then(res => {
        this.teacherData = res.data
      })
    },
    tableCellClassName({ row, column, rowIndex, columnIndex }) {
      // 注意这里是解构
      // 利用单元格的 className 的回调方法，给行列索引赋值
      row.index = rowIndex
      column.index = columnIndex
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.load(1, val)
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.load(val, this.size)
    },
    handleEdit(index, row) {
      console.log(index)
      // console.log(this.tableData[index].courseName + '---' + this.tableData[index].id)
      // 编辑
      if (this.currentTable === 1) {
        this.title = '编辑课程信息'
        // title = '新增课程班级信息'; form.id = form.name = form.hours = form.credit = ''
        this.form.id = this.tableData[index].id
        this.form.name = this.tableData[index].courseName
        this.form.hours = this.tableData[index].hours
        this.form.credit = this.tableData[index].credit
      } else if (this.currentTable === 2) {
        this.title = '编辑课程班级信息'
        // title = '新增课程班级信息'; form.id = form.name = form.hours = form.credit = ''
        this.form.id = this.tableData2[index].id
        this.form.name = this.tableData2[index].name
        this.form.classNum = this.tableData2[index].classNum
        // this.form.courseId = this.tableData2[index].course_id
        this.form.teacherName = this.tableData2[index].teacherName
        // this.form.teacherId = this.tableData2[index].teacher_id
      }
      // 弹出修改框
      this.dialog = true
    },
    handleDelete(index, row) {
      console.log(index, row)
      this.$confirm('确定要执行删除操作？删除后不可恢复')
        .then(_ => {
          // 调用api删除课程
          if (this.currentTable === 1) {
            apiCourse.deleteCurse(this.tableData[index].id).then(res => {
              // 重新加载视图
              this.load(this.current, this.size)
            })
          } else if (this.currentTable === 2) {
            // alert(this.tableData2[index].id)
            apiCourseClass.deleteCourseClass(this.tableData2[index].id).then(res => {
              // 重新加载视图
              this.load_2(null, null)
            })
          }
          this.$message({ showClose: true, message: '删除成功', type: 'success' })
        })
        .catch(_ => {
          this.$message({ showClose: true, message: '删除失败', type: 'warning' })
        })
    },
    // 单元格点击事件
    cell_click(row) {
      // console.log(row)
      console.log(row.index)
      console.log(this.tableData[row.index].id)
      this.form.courseId = this.tableData[row.index].id
      console.log(this.form.courseId)
      // this.form.teacherId = this.tableData[this.currentIndex].teacher_id
      this.myrow = row
      this.load_2(null, null)
    },
    // 弹出框
    handleClose(done) {
      if (this.loading) {
        return
      }
      this.$confirm('确定要提交表单吗？')
        .then(_ => {
          this.$message({ showClose: true, message: '正在执行操作。。。' })
          this.loading = true
          // 调用api添加课程信息
          if (this.currentTable === 1) {
            this.addCourse({ id: this.form.id, name: this.form.name, hours: this.form.hours, credit: this.form.credit })
          } else if (this.currentTable === 2) {
            this.updateCourseClass({
              id: this.form.id,
              name: this.form.name,
              courseId: this.form.courseId,
              classNum: this.form.classNum,
              // teacherName: this.form.teacherName,
              teacherId: this.form.teacherId
            })
          }
          done()
          this.loading = false
        })
        .catch(_ => {
          this.cancelForm()
        })
    },
    cancelForm() {
      this.loading = false
      this.dialog = false
      clearTimeout(this.timer)
    },
    addCourse(data) {
      apiCourse.addCourse(data).then(() => {
        this.timer = setTimeout(() => {
          this.$message({ showClose: true, message: '操作成功', type: 'success' })
          // 动画关闭需要一定的时间
          setTimeout(() => {
            this.loading = false
          }, 400)
          // 清除数据
          this.form.id = ''
          this.form.name = ''
          this.form.hours = ''
          this.form.credit = ''
          // 更新表格数据
          this.load(this.table_1.current, this.table_1.size)
        }, 2000)
      })
    },
    updateCourseClass(data, row) {
      console.log('提交的课程班级数据：')
      console.log(data)
      apiCourseClass.updateCourseClass(data).then(() => {
        this.timer = setTimeout(() => {
          this.$message({ showClose: true, message: '操作成功', type: 'success' })
          // 动画关闭需要一定的时间
          setTimeout(() => {
            this.loading = false
          }, 400)
          // 清除数据
          this.form.id = ''
          this.form.name = ''
          this.form.classNum = ''
          this.form.teacherName = ''
          this.form.teacherId = ''
          // 更新表格数据
          this.load_2(null, null)
        }, 2000)
      })
    }
  }
}
</script>

